﻿using WebApi.Commons.Helpers;
using WebApi.Models.Common;
using WebApi.Models.Database.DbName;
using WebApi.Models.Views.Account;
using WebApi.Repository;
using WebApi.Services.Interface;

namespace WebApi.Services
{
    /// <summary>
    /// 账号业务逻辑
    /// </summary>
    public class AccountService : IAccountService
    {
        #region 依赖注入

        private AccountRepository _accountRepository;

        private AccountLoginRepository _accountLoginRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="accountRepository"></param>
        /// <param name="accountLoginRepository"></param>
        /// <param name="groupMainRepository"></param>
        public AccountService(AccountRepository accountRepository, AccountLoginRepository accountLoginRepository)
        {
            _accountRepository = accountRepository;
            _accountLoginRepository = accountLoginRepository;
        }

        #endregion

        #region 接口实现

        /// <summary>
        /// 检查是否已经登录
        /// </summary>
        /// <param name="account">账号</param>
        /// <param name="password">密码</param>
        public LoginResponse Login(string account, string password)
        {
            #region 账号验证

            var result = new LoginResponse();
            if(string.IsNullOrEmpty(account) || string.IsNullOrEmpty(password))
            {
                return LoginResponse.Error("请输入用户名和密码");
            }

            if (!_accountRepository.CheckAccountValid(account))
            {
                return LoginResponse.Error("用户名或密码不正确");
            }

            var pwd = CommonHelper.GetMD5Password(account, password);
            var userInfo = _accountRepository.GetAccount(account, pwd);
            if(userInfo == null)
            {
                return LoginResponse.Error("用户名或密码不正确");
            }

            #endregion

            #region 生成Token

            var tokenData = new UserInfoModel
            {
                Id = userInfo.Id,
                Account = userInfo.Account,
                Name = userInfo.Name
            };

            var loginInfo = _accountLoginRepository.GetByAccountId(userInfo.Id);

            var token = IsValidToken(loginInfo) ? loginInfo.Token : JWTHelper.CreateJWTToken(tokenData);

            if (string.IsNullOrEmpty(token))
            {
                return LoginResponse.Error("登陆失败");
            }

            if(!AddOrUpdateLoginInfo(loginInfo, token, userInfo.Id))
            {
                return LoginResponse.Error("登陆失败");
            };

            result.UserData = tokenData;
            result.Token = token;
            result.Message = "登录成功";
            result.IsSuccess = true;
            return result;

            #endregion
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        public ResultInfoModel ResetPassword(ResetPasswordRequest request, UserInfoModel user)
        {
            var oldPwdEncry = CommonHelper.GetMD5Password(user.Account, request.OldPassword);
            var newPwdEncry = CommonHelper.GetMD5Password(user.Account, request.NewPassword);
            var data = _accountRepository.GetAccount(user.Account, oldPwdEncry);
            if (data == null)
            {
                return GetResult.Error("原密码错误");
            }
            if (_accountRepository.UpdatePassword(data.Id, newPwdEncry))
            {
                _accountLoginRepository.LoginOut(user.Id);
                return GetResult.Success("重置密码成功");
            }
            else
            {
                return GetResult.Error("重置密码失败");
            }
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 判断Token是否有效
        /// </summary>
        /// <param name="loginInfo"></param>
        /// <returns></returns>
        private bool IsValidToken(AccountLoginModel loginInfo)
        {
            //判断Token是否过期
            if (loginInfo == null || string.IsNullOrEmpty(loginInfo.Token) || loginInfo.ExpireTime < DateTime.Now || JWTHelper.IsExpired(loginInfo.Token))
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 新增或更新登录信息
        /// </summary>
        /// <param name="loginInfo"></param>
        /// <param name="token"></param>
        /// <param name="accoutId"></param>
        /// <returns></returns>
        private bool AddOrUpdateLoginInfo(AccountLoginModel loginInfo, string token, long accoutId)
        {
            var updateInfo = new AccountLoginModel
            {
                ExpireTime = DateTime.Now.AddMinutes(45),
                CreateTime = DateTime.Now,
                Token = token,
                AccountId = accoutId
            };
            if (loginInfo == null)
            {
                return _accountLoginRepository.Insert(updateInfo);
            }
            else
            {
                return _accountLoginRepository.UpdateLoginInfo(updateInfo);
            }
        }

        #endregion
    }
}
